package com.liu.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.liu.controller.dto.OrderDTO;
import com.liu.entity.*;
import com.liu.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * (Order)表控制层
 *
 * @author makejava
 * @since 2023-02-11 12:38:11
 */
@RestController
@RequestMapping("/order")
@CrossOrigin
@Slf4j
public class OrderController {

    // 注入Redis
    @Resource
    StringRedisTemplate stringRedisTemplate;

    /**
     * 服务对象
     */
    private OrderService orderService;
    @Autowired
    @Qualifier("orderServiceImpl")
    public void setService(OrderService orderService){
        this.orderService = orderService;
    }

    /**
     * 用户对象
     */
    private UserService userService;
    @Autowired
    @Qualifier("UserServiceImpl")
    public void setUserService(UserService userService){
        this.userService = userService;
    }

    /**
     * 医师对象
     */
    private PhysicianService physicianService;
    @Autowired
    @Qualifier("physicianServiceImpl")
    public void setPhysicianService(PhysicianService physicianService){
        this.physicianService = physicianService;
    }

    /**
     * 医院对象
     */
    private HospitalService hospitalService;
    @Autowired
    @Qualifier("hospitalServiceImpl")
    public void setService(HospitalService hospitalService){
        this.hospitalService = hospitalService;
    }

    /**
     * 科室对象
     */
    private DepartmentService departmentService;
    @Autowired
    @Qualifier("departmentServiceImpl")
    public void setService(DepartmentService departmentService){
        this.departmentService = departmentService;
    }

    /**
     * 阶段对象
     */
    private StageService stageService;
    @Autowired
    @Qualifier("stageServiceImpl")
    public void setService(StageService stageService){
        this.stageService = stageService;
    }

    /**
     * 个人订单
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/personOrder")
    public Map<String, Object> personOrder(@RequestParam Integer pageNum,
                                        @RequestParam Integer pageSize,
                                        @RequestParam(defaultValue = "") String num,
                                        @RequestParam(defaultValue = "") Integer id
    ){
        pageNum = (pageNum - 1) * pageSize;
        log.info("num:{}",num);
        List<Order> data = orderService.personOrder(pageNum, pageSize, num, id);
        Long total = orderService.orderCount(num,id);
        Map<String,Object> res = new HashMap<>();
        res.put("data",data);
        res.put("total",total);
        return res;
    }

    /**
     * 医生订单
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/phyOrder")
    public Map<String, Object> phyOrder(@RequestParam Integer pageNum,
                                           @RequestParam Integer pageSize,
                                           @RequestParam(defaultValue = "") String num,
                                            @RequestParam(defaultValue = "") String state,
                                           @RequestParam(defaultValue = "") Integer id
    ){
        pageNum = (pageNum - 1) * pageSize;
        log.info("num:{}",num);
        List<Order> data = orderService.phyOrder(pageNum, pageSize, num, id,state);
        Long total = orderService.phySaCount(num,id,state);
        Map<String,Object> res = new HashMap<>();
        res.put("data",data);
        res.put("total",total);
        return res;
    }

    /**
     * 医生当前订单
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/nowPhyOrder")
    public Map<String, Object> nowPhyOrder(@RequestParam Integer pageNum,
                                        @RequestParam Integer pageSize,
                                        @RequestParam(defaultValue = "") String num,
                                        @RequestParam(defaultValue = "") String state,
                                        @RequestParam(defaultValue = "") Integer id
    ){
        pageNum = (pageNum - 1) * pageSize;
        log.info("num:{}",num);
        List<Order> data = orderService.nowPhyOrder(pageNum, pageSize, num, id,state);
        Long total = orderService.nowSaCount(num,id,state);
        Map<String,Object> res = new HashMap<>();
        res.put("data",data);
        res.put("total",total);
        return res;
    }

    /**
     * 更新订单状态
     * @param id
     * @return
     */
    @PostMapping("/updateStage")
    public int updateStage(Integer id){
        return orderService.updateState(id);
    }

    /**
     * 人员总数
     * @return
     */
    @GetMapping("/count")
    public Long findCount(@RequestParam(defaultValue = "") String num) {
        return orderService.count(num);
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Map<String, Object> findPage(@RequestParam Integer pageNum,
                                        @RequestParam Integer pageSize,
                                        @RequestParam(defaultValue = "") String num
    ){
        pageNum = (pageNum - 1) * pageSize;
        log.info("num:{}",num);
        List<Order> data = orderService.queryAllByLimit(pageNum, pageSize, num);
        Long total = orderService.count(num);
        Map<String,Object> res = new HashMap<>();
        res.put("data",data);
        res.put("total",total);
        return res;
    }

    /**
     * 查询全部数据
     * @return
     */
    @GetMapping("/list")
    public List<Order> findAll(){
        return this.orderService.findAll();
    }

    /**
     * 查询所有用户
     *
     */
    @GetMapping("/findUser")
    public List<User> findAllUser(){
        return userService.findAllUser();
    }

    /**
     * 查询所有医师
     *
     */
    @GetMapping("/findPhy")
    public List<Physician> findPhy(){
        return physicianService.findAll();
    }

    /**
     * 查询全部医院
     * @return
     */
    @GetMapping("/findHos")
    public List<Hospital> findHos(){
        return hospitalService.findAll(null,null,null,null);
    }

    /**
     * 查询全部数据
     * @return
     */
    @GetMapping("/findDep")
    public List<Department> findDep(){
        return this.departmentService.findAll();
    }


    /**
     * 添加或更新订单
     *
     * @param order
     */
//    @PostMapping("/edit")
//    public int insert(@RequestBody Order order) {
//
//        log.info("当前保存或修改的信息:{}", order.toString());
//        //根据传递过来的参数Id是否存在来决定进入哪个方法
//        if (order.getId() != null && order.getId().toString().length() > 0) {
//                System.out.println(order.getId());
//                return orderService.update(order);
//            } else {
//                System.out.println(order.getId());
//                Stage stage = stageService.queryById(order.getStaId());
//                if (stage.getCount() == null){
//                    stage.setCount(1);
//                }else if (stage.getCount() >= stage.getNum()){
//                    return 0;
//                }
//                else {
//                    stage.setCount(stage.getCount()+1);
//                }
//                stageService.updateCou(stage.getCount(),stage.getId());
//                return orderService.insert(order);
//        }
//    }

    @PostMapping("/edit")
    public Integer saveOrder(@RequestBody Order order) {
        // 1. 判断订单是更新还是新增
        if (order.getId() != null && StringUtils.hasLength(order.getId().toString())) {
            System.out.println(order.getId());
            return orderService.update(order);
        }

        // 2. 新增订单：处理挂号逻辑（核心）
        int staId = order.getStaId();
        // 2.1 Redis预校验：快速判断是否有剩余名额，拦截无效请求
        String redisKey = "stage:remaining:" + staId;
        Long remaining = stringRedisTemplate.opsForValue().decrement(redisKey); // 原子减1（关键）
        if (remaining == null || remaining < 0) {
            // 若剩余名额不足，回滚Redis操作（加1），返回失败
            stringRedisTemplate.opsForValue().increment(redisKey);
            log.error("新增失败");
            return 0; // 超卖，新增失败
        }

        try {
            // 2.2 数据库乐观锁更新：保证最终一致性
            // 查询阶段最新数据（包含version）
            Stage stage = stageService.queryByIdWithVersion(staId); // 需自定义方法，查询id和version
            if (stage == null) {
                // 阶段不存在，回滚Redis
                stringRedisTemplate.opsForValue().increment(redisKey);
                log.error("阶段不存在，回滚Redis");
                return 0;
            }

            // 数据库层面二次校验（防止缓存与数据库短暂不一致）
            int currentRemaining = stage.getNum() - stage.getCount();
            if (currentRemaining <= 0) {
                stringRedisTemplate.opsForValue().increment(redisKey);
                log.error("无挂号名额");
                return 0;
            }

            // 2.3 乐观锁更新阶段已用名额（count+1）
            // SQL示例：UPDATE stage SET count = count + 1, version = version + 1
            // WHERE id = ? AND version = ? AND count < num
            int updateRows = stageService.updateCountWithOptimisticLock(staId, stage.getVersion());
            if (updateRows == 0) {
                // 乐观锁更新失败（版本不一致，说明被其他请求修改），回滚Redis
                stringRedisTemplate.opsForValue().increment(redisKey);
                log.error("版本不一致");
                return 0;
            }

            // 2.4 乐观锁更新成功，插入订单
            return orderService.insert(order);

        } catch (Exception e) {
            // 异常情况下回滚Redis，避免缓存数据错误
            stringRedisTemplate.opsForValue().increment(redisKey);
            throw e;
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/del")
    public int delete(Integer id){
        log.info("当前删除数据的id:{}", id);
        return orderService.deleteById(id);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping("/delBatch")
    public int deleteBatch(@RequestBody List<Integer> ids){
        return orderService.deleteByIds(ids);
    }

    /**
     * 导出文件
     * @param response
     * @throws Exception
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        //从数据库查询所有数据
        List<Order> list = orderService.findAll();
        //在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list,true);

        //设置浏览器响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset-utf-8");
        String fileName = URLEncoder.encode("订单信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();
    }

    /**
     * 导入文件
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public int  imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<Order> list = reader.readAll(Order.class);
        System.out.println(list);
        return orderService.insertBatch(list);
    }

    /**
     * 根据id查找
     * @param id
     * @return
     */
    @GetMapping("/findById")
    public Order queryById(Integer id){
        return orderService.queryById(id);
    }

}

